package com.newidea.jiangong.service.impi;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newidea.jiangong.entity.Weather;
import com.newidea.jiangong.mapper.WeatherServiceMapper;
import com.newidea.jiangong.service.WeatherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Service
@Slf4j
public class WeatherServiceImpl extends ServiceImpl<WeatherServiceMapper, Weather> implements WeatherService {


    private String url = "http://gfeljm.tianqiapi.com/api?unescape=1&version=v63&appid=24418736&appsecret=lNjG6gdl&cityid=";

    private String HAI_DIAN = "CN101010200";
    private String CHAO_YANG = "CN101010300";
    private String XIONG_AN = "CN101091201";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWeather() {
        // 当前时间就是采集时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String collectTime = LocalDateTime.now().format(formatter);

        // 采集北京海淀天气
        Weather haidian = JSONUtil.parseObj(HttpUtil.get(url + HAI_DIAN)).toBean(Weather.class);
        haidian.setCollect_time(collectTime);

        // 采集北京朝阳天气
        Weather chaoyang = JSONUtil.parseObj(HttpUtil.get(url + CHAO_YANG)).toBean(Weather.class);
        chaoyang.setCollect_time(collectTime);

        // 采集雄安新区天气
        Weather xiongan = JSONUtil.parseObj(HttpUtil.get(url + XIONG_AN)).toBean(Weather.class);
        xiongan.setCollect_time(collectTime);

        List<Weather> list = ListUtil.of(haidian, chaoyang, xiongan);
        this.saveBatch(list);

        log.info("采集天气成功");
    }
}
